package com.hzhq.contract.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author hzhq
 * @create 2021/4/9 3:14 下午
 * @email hzhq1255@163.com
 */
public class UpdateUtils {

    /**
     * 动态复制
     * @param source 源对象
     * @param target 目标对象
     *
     */
    public static void dynamicCopySameBean(Object source, Object target) {
        if (source.getClass().isInstance(target)){
            for (Field field: source.getClass().getDeclaredFields()){
                field.setAccessible(true);
                String key = field.getName();
                String getMethodName = "get" + key.substring(0,1).toUpperCase()+key.substring(1);
                String setMethodName = "set" + key.substring(0,1).toUpperCase()+key.substring(1);
                try {
                    if (null == field.get(source)){
                        continue;
                    }
                    Object value = source.getClass().getDeclaredMethod(getMethodName).invoke(source);
                    target.getClass().getMethod(setMethodName,value.getClass()).invoke(target,value);
                }catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
